<template>
    <el-row class="tac" v-loading="loading">
        <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
            <pane size="12">
                <el-scrollbar height="calc(100vh - 93px)">
                    <!-- <el-input v-model="rightTag.toolName" placeholder="工具名称" /> -->
                    <div
                        style="display: flex; justify-content: space-between; align-items: center; margin-top: 20px; margin-left: 10px;">

                        <div style="display: flex; justify-content: center; align-items: center;">
                            <el-icon style="color: #606266;">
                                <Menu />
                            </el-icon>
                            <el-text style="font-size: 16px; margin-left: 5px; font-weight: bold;">流程设计</el-text>
                        </div>
                        <div style="margin-right: 15px;">
                            <el-tooltip class="box-item" effect="dark" content="新增" placement="top">
                                <el-button type="primary" icon="CirclePlus" @click="handleAddNode()" link
                                    class="blue-icon hidden-md-and-down"></el-button>
                            </el-tooltip>
                            <el-tooltip class="box-item" effect="dark" content="修改名称" placement="top">
                                <el-button type="primary" icon="Edit" :disabled="disabled" @click="handleUpdateName()"
                                    link class="blue-icon hidden-md-and-down"></el-button>
                            </el-tooltip>

                            <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                                <el-button link type="primary" icon="Delete" :disabled="disabled" @click="handleDelete"
                                    class="blue-icon hidden-md-and-down"></el-button>
                            </el-tooltip>

                            <!-- <el-button type="primary" @click="handleMoreNodes()" link>更多</el-button> -->
                        </div>

                    </div>

                    <div style="padding: 5px;">
                        <div style="padding: 5px;">
                            <ul>
                                <li v-for="(item, index) in flowList" :key="index" @click="handleOpen(item, index)"
                                    @mouseover="handleMouseOver(index)" @mouseout="handleMouseOut(index)"
                                    :class="{ 'hovered': isHovered === index, 'clicked': isClicked === index }"
                                    style="margin-bottom: 5px;   border-radius: 8px; display: flex; justify-content: space-between; align-items: center;">
                                    <!-- <img :src="getSrc(item.appIconPath)" alt="" style="height: 25px; width: 25px;"> -->
                                    <div class="ellipsis-text" :title="item.name">
                                        {{ item.name }}
                                    </div>
                                    <!-- <el-tooltip class="box-item" effect="dark" :content="item.name" placement="right">
                                </el-tooltip> -->

                                    <div>
                                        <el-tooltip class="box-item" effect="dark" content="运行" placement="top">
                                            <el-button link type="primary" icon="CaretRight"
                                                @click.stop="handleWorking(item, index)"
                                                v-hasPermi="['vueflow:flow:working']"
                                                class="blue-icon hidden-md-and-down"></el-button>
                                        </el-tooltip>
                                        <el-tooltip class="box-item" effect="dark" content="打开xml" placement="top">
                                            <el-button link type="primary" icon="Open" @click.stop="openXml(item)"
                                                v-hasPermi="['vueflow:flow:openXml']"
                                                class="blue-icon hidden-md-and-down"></el-button>
                                        </el-tooltip>
                                        <el-tooltip class="box-item" effect="dark" content="复制xml" placement="top">
                                            <el-button link type="primary" icon="Crop" @click.stop="copyXml(item)"
                                                v-hasPermi="['vueflow:flow:copyXml']"
                                                class="blue-icon hidden-md-and-down"></el-button>
                                        </el-tooltip>
                                    </div>

                                </li>

                            </ul>
                        </div>
                    </div>

                </el-scrollbar>
            </pane>
            <pane size="88">


                <flow-design ref="designRef" v-if="activeIndex === '1'" v-model:flowData="flowData"
                    :switchActiveIndex="switchActiveIndex" :getHandleGetList="getHandleGetList"
                    v-model:contrast_node_string="contrast_node_string" />
                <flow-manage v-if="activeIndex === '2'" v-model:flowData="flowData"
                    :switchActiveIndex="switchActiveIndex" :getHandleGetList="getHandleGetList" />
            </pane>
        </splitpanes>
    </el-row>
</template>

<script lang="ts" setup>
import {
    Document,
    Menu as IconMenu,
    Location,
    Setting,
} from '@element-plus/icons-vue'
import FlowDesign from './FlowDesign.vue'
import FlowManage from './FlowManage.vue'
import { onMounted, ref } from 'vue';
import { getFlow, getRunXml, listFlow, delFlow, updateFlow, updateFlowName, listAllFlow, checkXmlPath, addFlow } from '../../../api/flow/flow';
import { listStandardAll } from '@/api/flow/standard'
import flowNodesStore from '@/store/modules/flowNodes'
import { fa, tr } from 'element-plus/es/locales.mjs';
import { ElMessageBox, ElMessage } from 'element-plus';
import 'element-plus/theme-chalk/display.css'
import { listAllFeatureTemplate } from '../../../api/flow/featureTemplate';
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import useAppStore from '@/store/modules/app'
const appStore = useAppStore()
const { proxy } = getCurrentInstance();
const flowNodes = flowNodesStore()
const activeIndex = ref('1');
const flowData = ref({});
const flowList = ref([])
const loading = ref(false);
const ids = ref();
const disabled = ref(true);
const designRef = ref();
const contrast_node_string = ref('');
onMounted(() => {
    getList();
})
const getList = () => {
    listAllFlow().then((response: any) => {
        response.data.forEach((item: any, index: number) => {
            item.name = '' + (index + 1) + '-' + item.name;
        });
        flowList.value = response.data;
    });


    listStandardAll().then((response: any) => {
        flowNodes.setStandardList(response.data);
    });

    listAllFeatureTemplate().then((response: any) => {
        flowNodes.setTemplateList(response.data);
    });
}

const getHandleGetList = () => {
    getList();
}

const switchActiveIndex = (index: string) => {
    activeIndex.value = index;
}

const handleAddNode = () => {
    switchActiveIndex("3");
    flowData.value = {}
    loading.value = true;

    nextTick(() => {
        loading.value = false;
        flowNodes.setFlowNodes([]);
        switchActiveIndex('1');

        isClicked.value = -1;
        isHovered.value = -1;
    });
}

const handleUpdateName = () => {
    proxy.$prompt('请输入新名称', "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(({ value }) => {
        // 检查 value 是否为空
        if (!value || value.trim() === '') {
            proxy.$modal.msgError('名称不能为空，请重新输入');
            return;
        }
        updateFlowName({
            id: ids.value,
            name: value
        }).then((response: any) => {
            proxy.$modal.msgSuccess("修改成功");
            getList();
        });
    }).catch(() => { })
}
const handleMoreNodes = () => {
    // console.log('handleMoreNodes');
    switchActiveIndex("2");
}

const handleOpen = (row: any, index: any) => {
    const loadFlowData = () => {
        switchActiveIndex("3");
        ids.value = row.id;
        isClicked.value = index;
        loading.value = true;
        disabled.value = false;
        getFlow(row.id).then((response: any) => {
            flowData.value = response.data;
            contrast_node_string.value = response.data.nodes;
            flowNodes.setFlowNodes(JSON.parse(response.data.nodes));
            loading.value = false;
            switchActiveIndex('1');
        });
    };

    if (row.id != isClicked.value) {
        if (isClicked.value >= 0) {
            if (contrast_node_string.value != JSON.stringify(flowNodes.getFlowNodes()) && activeIndex.value == '1') {
                proxy.$modal.confirm('是否确认保存当前流程数据？')
                    .then(() => designRef.value.handleSave())
                    .catch(() => { })
                    .finally(() => { // ✅ 修改为 finally()
                        loadFlowData();
                    });
            } else {
                loadFlowData();
            }
        } else {
            loadFlowData();
        }
    }
};

const handleWorking = (item: any, index: any) => {
    // 运行之前报一个是否允许
    proxy.$modal.confirm('是否运行该流程？').then(function () {
        getRunXml(item.id).then((res: any) => {
            if (res.data.xmlPath.includes("http")) {
                try {
                    window.location.href = `StartFlow://${res.data.xmlPath}`;
                } catch (error) {
                    ElMessage.error('请检查xml文件路径是否正确！');
                    console.log(error);
                }
            }
        });
    })

}


const openXml = (row: any) => {
    getRunXml(row.id).then((res: any) => {
        let obj = {
            xmlPath: row.xmlPath,
        }
        checkXmlPath(obj).then((checkRes: any) => {
            if (checkRes.code == 200) {
                window.open(res.data.xmlPath);
            }
        });
    });
}

const copyXml = (row: any) => {
    // 弹一个输入框输入新的名称后调用接口
    proxy.$prompt('请输入组件名称', "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(({ value }) => {
        row.id = null;
        row.name = value;
        addFlow(row).then((res: any) => {
            proxy.$modal.msgSuccess("复制成功");
            getList();
        })
    })
}


/** 删除按钮操作 */
const handleDelete = () => {
    const _ids = ids.value;
    proxy.$modal.confirm('是否确认删除该流程？').then(function () {
        return delFlow(_ids);
    }).then(() => {
        getList();
        handleAddNode();
        isClicked.value = -1;
        disabled.value = true;
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}


const isHovered = ref(-1);
const isClicked = ref(-1);

const handleMouseOver = (index: any) => {
    isHovered.value = index;
};

const handleMouseOut = (index: any) => {
    isHovered.value = -1;
};
</script>
<style scoped>
ul {
    list-style-type: none;
    padding: 0;
}

li {
    padding: 3px;
    cursor: pointer;
    color: #606266;
}

.hovered {
    background-color: #e0e0e0;
    /* 鼠标悬停时的背景颜色 */
}

.clicked {
    background-color: #b0e0e6;
    /* 点击时的背景颜色 */
}

.el-col-1 {
    flex: 0 0 4.1666666667%;
    max-width: 1%;
}

.ellipsis-text {
    width: fit-content;
    max-width: 14ch;
    /* 最多显示 7 个字符宽度 */
    white-space: nowrap;
    /* 禁止换行 */
    overflow: hidden;
    /* 超出部分隐藏 */
    text-overflow: ellipsis;
    /* 超出部分显示省略号 */
    font-size: 13px;
}

.blue-icon {
    color: #1296db;
}
</style>